package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * <p>
 *  User前端控制器
 * </p>
 *
 * @author HXG28
 * @Date 2025-04-30 11:51
 * @Version 1.0
 **/
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @GetMapping("/page")
    @ApiOperation("分页查询用户接口")
    public PageDTO<UserVO> queryUsersPage(UserQuery query){
        return userService.queryUsersPage(query);
    }
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void deleteUser(@PathVariable("id") Long userId) {
        userService.removeById(userId);
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public UserVO queryUserById(@PathVariable("id") Long userId) {
        //1.查询用户
        User user = userService.getById(userId);
        //2.处理vo
        return BeanUtil.copyProperties(user, UserVO.class);
    }
    @GetMapping
    @ApiOperation("根据id集合查询用户")
    public List<UserVO> queryUserByIds(@RequestParam("ids") List<Long> userIds) {
        //查询用户
        List<User> users = userService.listByIds(userIds);
        //处理VO
        return BeanUtil.copyToList(users, UserVO.class);
    }
    @PutMapping("{id/deduction/{money}")
    @ApiOperation("扣减用户余额")
    public void deduction(@PathVariable("id") Long id, @PathVariable("money") Integer money) {
        userService.deductionBalance(id,money);
    }
    @GetMapping("/list")
    @ApiOperation("根据复杂条件查询用户接口")
    public List<UserVO> queryUsers(UserQuery query) {
        //1.组织条件
        String username = query.getName();
        Integer status = query.getStatus();
        Integer minBalance = query.getMinBalance();
        Integer maxBalance = query.getMaxBalance();
        //2.查询用户
        List<User> users = userService.lambdaQuery()
                .like(username != null, User::getUsername, username)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
        //3.处理vo
        return BeanUtil.copyToList(users,UserVO.class);
    }
}
